/*
 * @description:
 * @Author: jhw
 * @Date: 2023-05-07 18:47:06
 * @LastEditors: jhw
 * @LastEditTime: 2024-06-05 18:01:36
 */
import { errorCodeType } from '@/utils/errorTypeCode';
import { HRequestConfig, InterceptorHooks, HResConfig } from './service';
import { ElMessage } from 'element-plus';
import { Recordable } from '@/vite-env';

export const interceptorHooks: InterceptorHooks = {
  requestInterceptor: (config: HRequestConfig) => {
    if (!config.withToken) return config;

    (config as Recordable).headers['token'] = localStorage.getItem('token');
    return config;
  },
  responseInterceptors: (res: HResConfig) => {
    // 获取状态码
    const code = res.data['code'];
    // 获取错误信息
    const msg = errorCodeType(code) || res.data['msg'];
    // 文件上传code为0
    if (code === 200 || code === 0) {
      // 返回原生相应头还没写
      // InternalAxiosRequestConfig 没有定义withToken属性 会报错
      if (res.config.withToken) return res;
      return res;
    } else {
      ElMessage.error(msg);
      return res;
    }
  },
  responseInterceptorsCatch(error) {
    if (error.response && error.response.status) {
      // 获取错误信息
      const msg = errorCodeType(error.response.status);
      return Promise.reject(ElMessage.error(msg));
    } else {
      return Promise.reject('请求失败！');
    }
  },
};
